package es

import (
	"github.com/olivere/elastic/v7"
	"github.com/sirupsen/logrus"
	"log"
	"os"
	"strings"
)

var (
	Client *elastic.Client
)

func MustInitES(endpoints []string, sniff bool, gzip bool, logLevel string) *elastic.Client {
	var (
		err       error
		version   string
		esSetting = make([]elastic.ClientOptionFunc, 0)
	)

	for idx := range endpoints {
		if version, err = Client.ElasticsearchVersion(endpoints[idx]); err != nil {
			logrus.Warnf("check es version by[%s] err: %v", endpoints[idx], err)
			continue
		}

		esSetting = append(esSetting, elastic.SetURL(endpoints[idx]))
	}

	if len(esSetting) == 0 {
		logrus.Panic("no es endpoint available")
	}

	esSetting = append(esSetting, elastic.SetSniff(sniff))
	esSetting = append(esSetting, elastic.SetGzip(gzip))

	switch strings.ToLower(logLevel) {
	case "error":
		esSetting = append(esSetting, elastic.SetErrorLog(log.New(os.Stderr, "=============== ES Err ===============\n", 0)))
	case "info":
		esSetting = append(esSetting, elastic.SetInfoLog(log.New(os.Stderr, "=============== Es Info ===============\n", 0)))
	case "trace":
		esSetting = append(esSetting, elastic.SetTraceLog(log.New(os.Stderr, "=============== ES Trace ===============\n", 0)))
	default:
		esSetting = append(esSetting, elastic.SetErrorLog(log.New(os.Stderr, "=============== ES Err ===============\n", 0)))
	}

	if Client, err = elastic.NewClient(esSetting...); err != nil {
		logrus.Panicf("init es client err: %v", err)
	}

	logrus.Infof("init es success, version: %s", version)

	return Client
}
